#include "TileSet.h"
// Constructor single Tile.
TileSet::TileSet(int tileWidth, int tileHeight)
{
	this->tileWidth = tileWidth;
	this->tileHeight = tileHeight;
}
// Constructor mulitple Tiles in one texture file.
TileSet::TileSet(std::string names, IDirect3DTexture9* texture, int tileWidth, int tileHeight)
{
	D3DSURFACE_DESC desc;
	texture->GetLevelDesc(0, &desc);
	if (desc.Width % tileWidth != 0 || desc.Height % tileHeight != 0)
		throw;

	this->tileWidth = tileWidth;
	this->tileHeight = tileHeight;

	int tilesWide = desc.Width / tileWidth;
	int tilesHigh = desc.Height / tileHeight;

	if (names.length() != (tilesWide * tilesHigh))
		throw;

	D3DXVECTOR3 position(0.0f, 0.0f, 0.0f);
	RECT rect;
	rect.left = 0;
	rect.top = 0;
	rect.right = tileWidth;
	rect.bottom = tileHeight;
	int tileNum = 0;
	// Cycle through texture to separate out each Tile.
	for (int y = 0; y < tilesHigh; ++y)
	{
		for (int x = 0; x < tilesWide; ++x)
		{
			Tile tile(rect, texture);
			tiles[names[tileNum]] = tile;
			++tileNum;
			rect.left += tileWidth;
			rect.right += tileHeight;
		}
		rect.left = 0;
		rect.top += tileHeight;
		rect.bottom += tileHeight;
	}
}

void TileSet::addTile(char name, Tile tile)
{
	// Add Tile of name to tiles.
	tiles[name] = tile;
}

void TileSet::removeTile(char name)
{
	// Search for Tile in tiles with a name and store iter position.
	std::map<char, Tile>::iterator found = tiles.find(name);
	// Test for iter position in tiles and erase tile from map.
	if (found != tiles.end())
		tiles.erase(found);
}

Tile TileSet::getTile(char name) const
{
	// Search for Tile in tiles with a name and store iter position.
	std::map<char, Tile>::const_iterator found = tiles.find(name);
	// Test for iter position in tiles and return the tile from
	// second column of the tiles map.
	if (found != tiles.end())
		return found->second;
	// Otherwise return a blank Tile.
	return Tile();
}